package com.sky.service.impl;

import cn.hutool.http.server.HttpServerResponse;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.service.*;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportServiceImpl implements ReportService {

    private final OrderService orderService;

    private final UserService userService;

    private final OrderDetailService orderDetailService;

    private final OrderMapper orderMapper;

    private final WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //每天的日期集合
        List<LocalDate> dateList = new ArrayList<>();
        //每天的营业额集合
        List<Double> amountList = new ArrayList<>();

        dateList.add(begin);
        while ( !begin.equals(end) ){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date : dateList) {
            //查询date日期已完成的订单
            LocalDateTime beginTime  = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime  = LocalDateTime.of(date, LocalTime.MAX);

            List<Orders> ordersList = orderService.lambdaQuery()
//                    .eq(Orders::getStatus, Orders.COMPLETED)
                    .eq(Orders::getStatus, Orders.CANCELLED)
                    .gt(Orders::getOrderTime, beginTime)
                    .lt(Orders::getOrderTime, endTime).list();

            //每天的营业额
            double sum = 0;

            for (Orders orders : ordersList) {
                Double amount = orders.getAmount().doubleValue(); // 获取订单金额
                sum +=amount;
            }

            amountList.add(sum);
        }



        TurnoverReportVO turnoverReportVO =
                TurnoverReportVO.builder()
                        .dateList(StringUtils.join(dateList, ","))
                        .turnoverList(StringUtils.join(amountList, ","))
                        .build();

        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //每天的日期集合
        List<LocalDate> dateList = new ArrayList<>();

        //date日期员工总数集合
        List<Long> userList = new ArrayList<>();
        //date日期新增的员工集合
        List<Long> userNewList = new ArrayList<>();

        dateList.add(begin);
        while ( !begin.equals(end) ){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for (LocalDate date : dateList) {
            //查询date日期员工总数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //查询date日期员工总数
            Long userCount = userService.lambdaQuery()
                    .lt(User::getCreateTime, endTime).count();

            //date日期新增的员工
            Long userNewCount = userService.lambdaQuery()
                    .gt(User::getCreateTime, beginTime)
                    .lt(User::getCreateTime, endTime).count();

            userList.add(userCount);
            userNewList.add(userNewCount);
        }

        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(userList, ","))
                .newUserList(StringUtils.join(userNewList, ","))
                .build();

        return userReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {

        //每天的日期集合
        List<LocalDate> dateList = new ArrayList<>();

        //每日订单数集合
        List<Integer> orderList = new ArrayList<>();

        //每日有效订单数集合
        List<Integer> orderListed = new ArrayList<>();

        //订单总数
        Integer orderSum = 0;
        //有效订单总数
        Integer orderedSum = 0;

        dateList.add(begin);
        while ( !begin.equals(end) ){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for (LocalDate date : dateList) {

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //每日订单数
            Integer orderCount = orderService.lambdaQuery()
                    .gt(Orders::getOrderTime, beginTime)
                    .lt(Orders::getOrderTime, endTime).count().intValue();

            //每日有效订单数
            Integer orderCounted = orderService.lambdaQuery()
                    .eq(Orders::getStatus, Orders.COMPLETED)
                    .gt(Orders::getOrderTime, beginTime)
                    .lt(Orders::getOrderTime, endTime).count().intValue();

            orderList.add(orderCount);
            orderListed.add(orderCounted);

            orderSum += orderCount;
            orderedSum +=orderCounted;
        }

        //订单完成率
        Double orderRate = orderedSum.doubleValue()/orderSum.doubleValue();

        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderList, ","))
                .validOrderCountList(StringUtils.join(orderListed, ","))
                .totalOrderCount(orderSum)
                .validOrderCount(orderedSum)
                .orderCompletionRate(orderRate)
                .build();

        return orderReportVO;
    }

    /**
     * 销售排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        //封装返回结果数据
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();

    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据--查询30天数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.
                getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //2.通过POI将数据写入Excel文件中
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获取表格文件的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间" + begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //3.通过输出流将Excel文件下载到客户端游览器

    }
}
